﻿var me = this,
    vm = this.lookupViewModel(),
    controller = this.lookupController();

var viewStatus = this.lookupController().analysis().status;

if (viewStatus == 'launch' || viewStatus == 'resubmit') {
    var paList = vm.get('NebulogyForm.ProjectActivityList');
    var column = view.ownerCt.getColumnManager().getHeaderAtIndex(cellIndex);

    var index = ref.datagrid1.getSelectionModel().selectionStartIdx;
    var rec = ref.datagrid1.store.getAt(index);
    if (column.dataIndex == 'ProjectActivity') {

        var isInquiryCall = vm.get('NebulogyForm.isInquiryCall');
        if (!isInquiryCall) {

            //弹出窗
            var window1 = Ext.create('Ext.window.Window', {
                title: 'Project Activity',
                height: 560,
                width: 600,
                modal: true,
                layout: {
                    type: 'float',
                    columns: 1
                },
                buttons: [{
                    xtype: "button",
                    text: "Confirm",
                    handler: function () {
                        var win = this.up("window"),
                            refs = win.getReferences();
                        //赋值 

                        var selectRecord = refs.grid.getSelection();
                        if (selectRecord.length > 0) {

                            var pa = selectRecord[0].get('ProjectActivity');
                            var a = controller.getBalance(pa, null, function () {
                                return true;
                            });

                            if (!a) {
                                record.set('ProjectActivity', pa);
                                window1.close();
                            }
                        }
                    }
                }, {
                    xtype: "button",
                    text: "Cancel",
                    handler: function () {
                        this.up("window").close();
                    }
                }],
                //主视图内部控件
                referenceHolder: true,
                items: [{
                    xtype: 'paigrid',
                    reference: 'grid',
                    flex: 10,
                    enableAdd: false,
                    enableDel: false,
                    enableSearch: false,
                    dockedItems: [{
                        xtype: 'toolbar',
                        dock: 'top',
                        items: [{
                            xtype: 'textfield',
                            name: 'searchField',
                            flex: 300
                        }, '->', {
                            xtype: 'button',
                            text: 'Search',
                            handler: function () {
                                var store = this.up('paigrid').getStore();
                                var searchField = this.up("window").down('textfield[name=searchField]').getValue().toLowerCase();

                                if (searchField) {
                                    store.filterBy(function (record) {
                                        var lowcasePA = record.get('ProjectActivity').toString().toLowerCase();

                                        return lowcasePA.indexOf(searchField) != -1;
                                    });
                                } else {
                                    store.clearFilter();
                                }

                            }
                        }]
                    }],
                    columns: [{
                        text: 'Project Activity',
                        dataIndex: 'ProjectActivity',
                        flex: 1
                    }],
                    store: Ext.create('Ext.data.Store', {
                        fields: ['ProjectActivity'],
                        data: paList
                    }),
                    listeners: {
                        itemdblclick: function (grid, r) {
                            var pa = r.get('ProjectActivity');
                            var a = controller.getBalance(pa, null, function () {
                                return true;
                            });

                            if (!a) {
                                record.set('ProjectActivity', pa);
                                window1.close();
                            }
                        }
                    }
                }],
                listeners: {
                    close: function () {
                        Ext.getBody().unmask();
                    }
                }
            }).show();
        }
    } else if (column.dataIndex == 'MaterialGroup') {
        var segmentData = [];
        var Material_Group_NameArr = [];
        var MGCodeDecsriptionArr = [];
        //文本框内原本的值
        var mgValue = record.get('MaterialGroup');

        //获取Material Group数据.
        Ext.PAIRest.request({
            ns: PAI.application.url,
            url: 'last/materialGroup/page?_dc=' + Date.now(),
            method: "POST",
            async: false,
            data: {},
            success: function (data) {

                Ext.each(data.materialGroupList, function (record) {
                    //Segment 数据
                    segmentData.push({
                        name: record.segment,
                        value: record.segment
                    });

                    //Segment 数据
                    Material_Group_NameArr.push({
                        name: record.name,
                        value: record.name,
                        segment: record.segment
                    });

                    //Material Group Code & Decsription 数据
                    MGCodeDecsriptionArr.push({
                        code: record.code,
                        name: record.code + ' ' + record.description,
                        value: record.code + ' ' + record.description,
                        segment: record.segment,
                        parent: record.name
                    });
                });
                var obj = {};
                segmentData = segmentData.reduce(function (item, next) {
                    obj[next.name] ? '' : obj[next.name] = true && item.push(next);
                    return item;
                }, []);
            }
        });

        var win = Ext.create('Ext.window.Window', {
            title: 'Material Group',
            width: 600,
            height: 450,
            modal: true,
            padding: 10,
            layout: {
                type: 'float',
                columns: 1
            },
            cls: 'form-theme landRover',
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: ['->', {
                    xtype: 'segmentedbutton',
                    width: 300,
                    items: [
                        { text: 'NPP', name: 'NPP', pressed: true },
                        { text: 'Tooling', name: 'Tooling' }
                    ],
                    listeners: {
                        change: function (btn, newValue) {

                            var Segment = win.down('combo[name=Segment]');
                            var Material_Group_Name = win.down('combo[name=Material_Group_Name]');
                            var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
                            var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');

                            Segment.setValue('');

                            Material_Group_Name.setValue('');
                            Material_Group_Name.setReadOnly(true);

                            MGCodeDecsription.setValue('');
                            MGCodeDecsription.setReadOnly(true);

                            MGCodeDecsriptionForTooling.setValue('');
                            if (newValue != null) {
                                Material_Group_Name.hide();
                                //NPP Click
                                if (newValue == 0) {
                                    Segment.show();
                                    MGCodeDecsription.show();

                                    MGCodeDecsriptionForTooling.hide();
                                } else {
                                    Segment.hide();
                                    MGCodeDecsription.hide();

                                    MGCodeDecsriptionForTooling.show();
                                    MGCodeDecsriptionForTooling.setReadOnly(false);
                                    MGCodeDecsriptionForTooling.currentFilter = function (r) {
                                        return true;
                                    };
                                }
                            }
                        }
                    }
                }, '->']
            }],
            buttonAlign: 'center',
            buttons: [{
                text: 'Confirm',
                handler: function () {
                    var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
                    var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');
                    var npp_tooling = win.down('segmentedbutton').getValue();

                    var mgCtr = npp_tooling == 0 ? MGCodeDecsription : MGCodeDecsriptionForTooling;

                    if (!mgCtr.getValue()) {
                        mgCtr.focus();
                    } else {
                        var fieldSelectRecord = mgCtr.getSelectedRecord();

                        record.set('MaterialGroup', fieldSelectRecord.get('name'));
                        record.set('materialCode', fieldSelectRecord.get('code'));
                        win.close();
                    }
                }
            }, {
                text: 'Cancel',
                handler: function () {
                    win.close();
                }
            }],
            defaults: {
                width: 580,
                labelWidth: 200,
                labelAlign: 'top'
            },
            items: [{
                fieldLabel: 'Segment',
                name: 'Segment',
                xtype: 'combo',
                queryMode: 'local',
                displayField: 'name',
                valueField: 'value',
                store: segmentData,
                listeners: {
                    change: function (combo, newValue) {

                        var Material_Group_Name = win.down('combo[name=Material_Group_Name]');
                        var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');

                        var npp_tooling = win.down('segmentedbutton').getValue();
                        Material_Group_Name.store.clearFilter();
                        if (npp_tooling == 0) {
                            MGCodeDecsription.setValue('');
                            MGCodeDecsription.setReadOnly(false);

                            MGCodeDecsription.currentFilter = function (r) {
                                return r.get('segment') == newValue;
                            };
                        } else {
                            Material_Group_Name.setValue('');
                            Material_Group_Name.setReadOnly(false);

                            Material_Group_Name.currentFilter = function (r) {
                                return r.get('segment') == newValue;
                            };
                        }
                    }
                }
            }, {
                fieldLabel: 'Material Group Name',
                name: 'Material_Group_Name',
                xtype: 'combo',
                queryMode: 'local',
                displayField: 'name',
                valueField: 'value',
                store: new Ext.create('Ext.data.Store', {
                    fields: [
                        { name: 'name', type: 'string' },
                        { name: 'value', type: 'string' }
                    ],
                    data: Material_Group_NameArr
                }),
                listeners: {
                    select: function (combo, record) {
                        var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');

                        MGCodeDecsription.setValue('');
                        MGCodeDecsription.setReadOnly(false);

                        MGCodeDecsription.currentFilter = function (r) {
                            return r.get('parent') == record.get('value');
                        };
                    },
                    beforequery: beforequery
                }
            }, {
                fieldLabel: 'Material Group Code & Decsription',
                name: 'MGCodeDecsription',
                xtype: 'combo',
                queryMode: 'local',
                displayField: 'name',
                valueField: 'name',
                anyMatch: true,
                store: new Ext.create('Ext.data.Store', {
                    fields: [
                        { name: 'name', type: 'string' },
                        { name: 'value', type: 'string' }
                    ],
                    data: MGCodeDecsriptionArr
                }),
                listeners: {
                    beforequery: beforequery
                }
            }, {
                fieldLabel: 'Material Group Code & Decsription',
                name: 'MGCodeDecsriptionForTooling',
                xtype: "combo",
                hidden: true,
                displayField: 'name',
                valueField: 'name',
                anyMatch: true,
                store: {
                    type: 'budict',
                    sorters: [{
                        property: 'orderIndex',
                        direction: 'DESC'
                    }],
                    code: '2b32ea77-8fb4-4257-8d61-c00ca450a075'
                },
                queryMode: "local",
                listeners: {
                    beforequery: beforequery
                }
            }]
        });
        win.show();

        //如果是第二次填写 还需要回写值.
        if (mgValue) {
            var Segment = win.down('combo[name=Segment]');
            var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
            var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');
            var npp_tooling = win.down('segmentedbutton');

            var obj = MGCodeDecsriptionArr.filter(function (obj) {
                return obj.name == mgValue;
            });

            if (obj.length) {
                MGCodeDecsription.setReadOnly(false);
                Segment.setValue(obj[0].segment);
                MGCodeDecsription.setValue(mgValue);
            } else {
                npp_tooling.items.items[1].setPressed(true);
                MGCodeDecsriptionForTooling.setValue(mgValue);
            }
            //如果有值 但是值对不上NPP的数据.则就是Tooling的数据字典.
        }
    }
}

function beforequery(e) {
    var value = e.query;
    var combo = e.combo;

    combo.store.clearFilter();
    combo.store.filterBy(combo.currentFilter);

    if (!e.forceAll) {
        // 检索的正则
        var regExp = new RegExp(".*" + value.toLowerCase() + ".*");
        // 执行检索
        combo.store.filterBy(function (record, id) {
            // 得到每个record的项目名称值
            var text = record.get(combo.displayField);
            return regExp.test(text.toLowerCase());
        });
        combo.expand();
        return false;
    }
}